/** * This program finds the transpose of a matrix entered by the user. * The main method asks for the user to enter a matrix, and then calls * transpose() to do the transposition. The result matrix is then * printed. */ class Transpose { public static void main (String[] args) { // DECLARE VARIABLES/DATA DICTIONARY int[][] a; // GIVEN: A matrix of integers int nRows; // GIVEN: Number of rows in a. int nCols; // GIVEN: Number of columns in a. int[][] at; // RESULT: Transpose of a // PRINT OUT IDENTIFICATION INFORMATION System.out.println(); System.out.println("ITI 1120 Fall 2006, Lab 10, Example 2"); System.out.println("Name: Diana Inkpen, Student# 123456"); System.out.println(); // READ IN GIVENS System.out.println( "Enter the number of rows in matrix A: " ); nRows = ITI1120.readInt( ); System.out.println( "Enter the number of columns in matrix A: " ); nCols = ITI1120.readInt( ); a = MatrixLib.readIntMatrix( nRows, nCols ); // BODY OF ALGORITHM at = transpose( a ); // PRINT OUT RESULTS AND MODIFIEDS System.out.println( ); System.out.println( "The transposed matrix AT is: " ); System.out.println( ); MatrixLib.printMatrix( at ); } // If the 'main' method calls other algorithms, put the method(s) below. /** * This method transposes matrix 'a', returning matrix 'at'. * * Matrix a is assumed to be rectangular. The dimensions are not passed * as parameters; instead, the dimensions are determined from the * array lengths. * * GIVENS: a: an nRows x nCols matrix containing integers */ public static int[][] transpose( int[][] a ) { // DECLARE VARIABLES / DATA DICTIONARY int nRows; // GIVEN: number of columns in a, rows in b int nCols; // GIVEN: number of columns in b and c int[][] at; // RESULT: the transpose of matrix a int tRow; // INTERMEDIATE: index for row position in at int tCol; // INTERMEDIATE: index for column position in at // BODY OF ALGORITHM nRows = a.length; // number of rows in a nCols = a[0].length; // number of columns in a: this uses the // assumption that the matrix is a rectangle // so we can can use the length of any row. // Create result matrix. Be careful with dimensions! at = new int[nCols][nRows]; // Loop through each matrix position in at: for ( tRow = 0; tRow < nCols; tRow = tRow + 1 ) { for ( tCol = 0; tCol < nRows; tCol = tCol + 1 ) { at[tRow][tCol] = a[tCol][tRow] ; } } // RETURN RESULT return at; } }